package com.wizz.trade.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.wizz.trade.common.ServiceException;
import com.wizz.trade.excel.BuyConfirmTemplate;
import com.wizz.trade.excel.ExcelBuildParams;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author fyftless
 */
public class ExcelUtil {

    /**
     * 根据传入的数据集合导出excel
     *
     * @param response response
     * @param params   参数集合
     */
    public static void exportExcelWithList(HttpServletResponse response, ExcelBuildParams params) {
        //设定响应类型
        response.setContentType("application/vnd.ms-excel");
        //检验命名合法性
        if (!(params.getFileName().endsWith(".xls") || params.getFileName().endsWith(".xlsx"))) {
            throw new ServiceException("文件名非法");
        }
        //创建xls/xlsx文件
        try {
            //设定附件打开方式为<下载>,并指定文件名
            response.setHeader("content-disposition", "attachment;filename=" +
                    URLEncoder.encode(params.getFileName(), "UTF-8"));
            //获取输出流
            ServletOutputStream outputStream = response.getOutputStream();
            EasyExcel.write(outputStream, params.getClazz())
                    //开启列宽自适应
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    //自定义表格式
                    .registerWriteHandler(getStyleStrategy())
                    .sheet()
                    .doWrite(params.getData());
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            throw new ServiceException("excel导出失败");
        }
    }

    /**
     * 根据本地模板填充excel
     *
     * @param response response
     * @param params   参数
     */

    public static void exportExcelWithLocalTemplate(HttpServletResponse response, ExcelBuildParams params) {

        //设定响应类型
        response.setContentType("application/vnd.ms-excel");
        //检验命名合法性
        if (!(params.getFileName().endsWith(".xls") || params.getFileName().endsWith(".xlsx"))) {
            throw new ServiceException("文件名非法");
        }
        //载入模板路径
        //  String templateFileName = params.getTemplatePath();
        //创建excel文件
        try {
            //设定附件打开方式为<下载>,并指定文件名
            response.setHeader("content-disposition", "attachment;filename=" +
                    URLEncoder.encode(params.getFileName(), "UTF-8"));
            //获取输出流
            ServletOutputStream outputStream = response.getOutputStream();
            //根据模板填充excel
            ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(params.getInputStream()).
                    registerWriteHandler(getStyleStrategy()).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(params.getForceNewRow()).build();
            if (params.getData() != null) {
                excelWriter.fill(params.getData(), fillConfig, writeSheet);
            }
            if (params.getMap() != null) {
                excelWriter.fill(params.getMap(), writeSheet);
            }
            excelWriter.finish();

            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            throw new ServiceException("excel导出失败");
        }
    }

    /**
     * 根据用户上传的模板填充excel
     *
     * @param file     模板文件
     * @param response response
     * @param params   参数
     * @throws IOException
     */
    public static void exportExcelWithTemplateByUpload(MultipartFile file, HttpServletResponse response,
                                                       ExcelBuildParams params) {

        //设定响应类型
        response.setContentType("application/vnd.ms-excel");
        //检验命名合法性
        if (!(params.getFileName().endsWith(".xls") || params.getFileName().endsWith(".xlsx"))) {
            throw new ServiceException("文件名非法");
        }
        //创建excel文件
        try {
            //设定附件打开方式为<下载>,并指定文件名
            response.setHeader("content-disposition", "attachment;filename=" +
                    URLEncoder.encode(params.getFileName(), "UTF-8"));
            //获取输入流
            InputStream inputStream = file.getInputStream();
            //获取输出流
            ServletOutputStream outputStream = response.getOutputStream();
            //根据模板填充excel
            ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(params.getForceNewRow()).build();
            if (params.getData() != null) {
                excelWriter.fill(params.getData(), fillConfig, writeSheet);
            }
            if (params.getMap() != null) {
                excelWriter.fill(params.getMap(), writeSheet);
            }
            excelWriter.finish();
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            throw new ServiceException("excel导出失败");
        }
    }

    public static HorizontalCellStyleStrategy getStyleStrategy() {
        // 列头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 背景设置为灰色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());

        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 12);
        // 字体样式
        headWriteFont.setFontName("宋体");
        headWriteCellStyle.setWriteFont(headWriteFont);
        //自动换行
        headWriteCellStyle.setWrapped(true);
        // 水平对齐方式
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 垂直对齐方式
        headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // 内容的策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
//        contentWriteCellStyle.setFillPatternType(FillPatternType.SQUARES);
        // 背景白色
        contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setFontHeightInPoints((short) 12);
        // 字体样式
        contentWriteFont.setFontName("宋体");
        contentWriteCellStyle.setWriteFont(contentWriteFont);

        // 对齐策略
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 自动换行
        contentWriteCellStyle.setWrapped(true);
        return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    }
}
